package com.sds.sweng.swat.miplatform.ui.design.models.area.sub;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.PropertyDescriptor;

import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformComponent;
import com.sds.sweng.swat.miplatform.ui.design.models.component.MColumn;
import com.sds.sweng.swat.miplatform.ui.design.models.component.MTable;

public class TableSubArea extends SubArea {

	public static final String
		TABLE = "table";

	static {
		descriptors = new IPropertyDescriptor[] {
			new PropertyDescriptor(TABLE, "Table")
		};
	}

	private MTable table;

	public TableSubArea() {
		List<MColumn> columns = new ArrayList<MColumn>();
		List<TableCellSubArea> tableCells = new ArrayList<TableCellSubArea>();

		MTable table = new MTable();
		table.setColumns(columns);
		table.setTableCells(tableCells);

		setTable(table);
	}

	public TableSubArea clone() {
		TableSubArea clone = (TableSubArea) super.clone();
		clone.setTable(getTable().clone());

		return clone;
	}

	public MTable getTable() {
		return table;
	}

	public void setTable(MTable table) {
		this.table = table;

		removeChildren();

		for (int i=0;i<table.getTableCells().size();i++) {
			addChild(table.getTableCells().get(i));
		}

		firePropertyChange(TABLE, null, table);
	}

	@JsonIgnore
	public List<MiplatformComponent> getChildren() {
		return super.getChildren();
	}

	@JsonIgnore
	public void setChildren(List<MiplatformComponent> children) {
		super.setChildren(children);
	}

	public Object getPropertyValue(Object id) {
		if (TABLE.equals(id))
			return getTable();

		return null;
	}

	public void setPropertyValue(Object id, Object value) {
		if (TABLE.equals(id))
			setTable((MTable) value);
	}

	public void addChild(MiplatformComponent child, int index) {
		if (index >= 0)
			children.add(index, child);
		else
			children.add(child);

		fireStructureChange(CHILDREN, child);
	}

	public void removeChild(MiplatformComponent child) {
		children.remove(child);

		fireStructureChange(CHILDREN, child);
	}

	@Override
	public boolean isEmpty() {
		if (table.getTableCells().size() > 0)
			return false;

		return true;
	}

	@Override
	public int getRemainWidth() {
		return 0;
	}

	public boolean isFixed() {
		return true;
	}

	@Override
	public int getRequireWidth() {
		return getWidth();
	}

}
